package com.yrk.listener;

import com.yrk.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.ArrayList;
import java.util.List;
@WebListener
public class OnlineUserListener implements HttpSessionAttributeListener, ServletContextListener {
    ServletContext servletContext = null;
    /*
    *服务器启动时
    */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //创建集合存放在线用户
        List<User> users = new ArrayList<User>();
        //创建servletContext对象
        servletContext = servletContextEvent.getServletContext();
        //将集合存放在servletContext作用域中
        servletContext.setAttribute("users", users);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
/*
* 有新用户登录时触发
* */
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        //获得当前在线用户
        User user = (User) httpSessionBindingEvent.getSession().getAttribute("user");
        // 从application作用域中取出在线用户集合
        List<User> onLineUsers = (List<User>) servletContext.getAttribute("onLineUsers");
        //将新登录用户放入集合
        onLineUsers.add(user);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        //获得登录用户
        User user = (User) httpSessionBindingEvent.getValue();
        List<User> onLineUsers = (List<User>) servletContext.getAttribute("onLineUsers");
        onLineUsers.remove(user);
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}
